package test2;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 客户端
 */
public class Home04ClientB {
    public static void main(String[] args) throws Exception {
        try (Socket socket = new Socket("127.0.0.1",9999);
            Scanner scanner = new Scanner(System.in);
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream())){

            InputStreamReader isr = new InputStreamReader(bis);
            BufferedReader br = new BufferedReader(isr);
            System.out.println("请输入要查找的歌名");
            String name = scanner.next();
            //将要查找的歌名发送给服务器
            bos.write(name.getBytes(),0,name.getBytes().length);
            bos.flush();//清空缓存区

            while (true){
                int flog = bis.read();
                if(flog == -1){
                    System.out.println("查找结束....");
                    break;
                }
                name = UtilAPi.streamToString(br);//返回名字
                byte[]array = UtilAPi.getByteArray(bis);//返回文件
                try (OutputStream ops = new FileOutputStream("src/music/"+name)){
                    ops.write(array);//将该文件写入新地址
                    ops.flush();
                }
            }

        }
    }
}
